<?php
/**
 * 收益 api
 * @author maniac
 */
namespace app\api\controller\v1;

use app\facade\Profit AS ProfitFacade;
use app\common\model\MemberProfits AS MemberProfitsModel;
use app\common\model\Members AS MembersModel;
use app\facade\Site AS SiteFacade;

class Profit extends Base
{
    /**
     * 收益列表
     */
    public function profitList()
    {
        $userId = $this->checkUserToken();
        $page   = input('post.page/d', 1);
        $limit  = input('post.limit/d', 10);
        $offset = ($page - 1) * $limit;
        $limit  = $offset .','. $limit;
        $where  = [
            'wechat_id' => $userId,
        ];
        try {
            $app  = SiteFacade::appInfo();
            $data = [
                'list'           => ProfitFacade::profitList($where, $limit),
                'profits'        => MembersModel::where('wechat_id', $userId)->value('profit'),
                'min_cash_money' => $app['min_cash_money'],
            ];
            return j(0, '获取信息成功', $data);
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
    
    /**
     * 收益图表数据
     */
    public function profitCharts()
    {
        $userId = $this->checkUserToken();
        $times  = [];
        for ($i = 7; $i >= 1; $i--) {
            $times[] = strtotime(date('Y-m-d', time())) - $i*24*60*60;
        }
        $where = [
            ['wechat_id', 'eq', $userId],
            ['datetime', 'in', $times],
        ];
        $profits    = MemberProfitsModel::field('profit,datetime')->where($where)->select();
        $categories = [];
        $yData      = [];
        foreach ($profits as $v) {
            $categories[] = date('Y-m-d', $v['datetime']);
            $yData[]      = (float)$v['profit'];
        }
        $data  = [
            'categories' => $categories,
            'yData'      => $yData,
        ];
        return j(0, '获取数据成功', $data);
    }
    
    /**
     * 申请提现
     */
    public function cash()
    {
        $userId = $this->checkUserToken();
        $money  = input('post.money/d', 0);
        try {
            $result = ProfitFacade::cash($userId, $money);
            if ($result) {
                return j(0, '申请提现成功');
            }
            return j(1, '申请提现失败');
        } catch (\Exception $e) {
            return j(1, $e->getMessage());
        }
    }
}
